<script setup>
import {defineProps, onMounted, ref} from "vue";
import MyUserAnswerPage from "@/components/userAnswer/MyUserAnswerPage.vue";
import {Clock, Refresh, Trophy} from "@element-plus/icons-vue";
import {GetUserAnswerById} from "@/api/userAnswer.js";
import userAvatar from "@/views/user/UserAvatar.vue";
import {GetQuestionVOById} from "@/api/question.js";

const props = defineProps({
  appId: {
    type: String,
    default: ""
  }
});
const userAnswerData = ref(null)
const QuestionData = ref(null)
const userAnswerId = ref(null);
const CorrectOption = ref([]);
const handleDataLoaded = async (data) => {
  console.log('数据已加载:', data);
  userAnswerId.value = data[0].id??null;
  if(userAnswerId.value){
    const res = await GetUserAnswerById(userAnswerId.value);
    userAnswerData.value = res.data;
  }
  if(userAnswerData){
    console.log("userAnswerData: ",userAnswerData.value)
    if(userAnswerData.value.appType === 0){
      const question_data = await GetQuestionVOById(Number(props.appId));
      console.log("question_data: ",question_data)
      if(question_data.data) {
        console.log("1")
        QuestionData.value = JSON.parse( question_data.data.questionContent);
        console.log("QuestionData: ", QuestionData.value)
        CorrectOption.value = QuestionData.value.map(question => {
          const highestScoreOption = question.options.reduce((max, option) => {
            return option.score > max.score ? option : max;
          }, question.options[0]); // 这里添加了分号
          return highestScoreOption.key; // 添加了 return 语句
        }); // 这里闭合了 map 的回调函数
        console.log("CorrectOption: ",CorrectOption.value)
    }
  }

  // 可以在这里处理数据或设置标志位
}};
// 子组件点击行
const handleRowClick = (rowId) => {
  console.log('Received row ID:', rowId);
  // 在这里调用你想要的方法，例如：
  someMethod(rowId);
};

const someMethod = async (rowId) => {
  // 在这里实现你的逻辑
  const res = await GetUserAnswerById(rowId);
  userAnswerData.value = res.data;
};
// 用户但处理
  const formatChoices = (choices) => {
    if (!choices) return '';
    // 扁平化数组并清理字符串中的引号和换行符
    const flatChoices = choices.flat();
    return flatChoices.map(choice =>
        choice.replace(/\n"/g, '').trim()
    ).join(', ');
  };
</script>

<template>
  <div class="result-container">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧信息展示 -->
      <div class="info-section">
        <el-card class="info-card" v-if="userAnswerData">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Trophy /></el-icon>
                测评结果详情
              </span>
              <el-button type="primary" size="small" @click="handleDataLoaded" style="font-size: 13px">
                <el-icon><Refresh /></el-icon>
                刷新数据
              </el-button>
            </div>
          </template>

          <div  class="info-list">
            <div class="info-item">
              <span class="info-label">结果名称:</span>
              <el-tag type="success" effect="dark" class="info-value" style="font-size: 16px;;display: flex;justify-content: center;align-content: center">
                {{ userAnswerData.resultName || '未设置' }}</el-tag>
            </div>

            <div class="info-item">
              <span class="info-label">结果描述:</span>
              <el-tooltip effect="light" :content="userAnswerData.resultDesc" placement="top" style="font-size: 16px;;display: flex;justify-content: center;align-content: center">
                <span class="info-value description-text">{{ userAnswerData.resultDesc || '无描述信息' }}</span>
              </el-tooltip>
            </div>

            <div class="info-item">
              <span class="info-label">结果ID:</span>
              <code class="info-value id-code">{{ userAnswerData.id || 'N/A' }}</code>
            </div>

            <div  class="info-item" v-if="userAnswerData.appType === 0">
              <span class="info-label" >得分:</span>
              <el-tag :type="userAnswerData.resultScore >= 60 ? 'success' : 'danger'" effect="plain" size="large" class="info-value" style="font-size: 16px" >
                {{ userAnswerData.resultScore || 0 }} 分
              </el-tag>
            </div>
            <div  class="info-item">
              <span class="info-label">我的答案:</span>
              <el-tag effect="plain" size="large" class="info-value" style="font-size: 16px;">
                {{ formatChoices(userAnswerData.choice) || '无答案' }}
              </el-tag>
            </div>
            <div  class="info-item"  v-if="userAnswerData.appType===0&&CorrectOption">
              <span class="info-label">正确答案:</span>
              <el-tag effect="plain" size="large" class="info-value" style="font-size: 16px;">
                {{ CorrectOption || '无答案' }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间:</span>
              <span class="info-value time-text">
                <el-icon><Clock /></el-icon>
                {{ userAnswerData.createTime || '未知时间' }}
              </span>
            </div>

            <div class="info-item">
              <span class="info-label">用户:</span>
              <span class="info-value user-info">
                <el-avatar :size="32" :src="userAnswerData.user.user_pic" />
                <span class="user-name">{{ userAnswerData.user.username || '匿名用户' }}</span>
              </span>
            </div>
          </div>

          <div class="additional-info">
            <el-alert
                v-if="userAnswerData?.scoringStrategy !== undefined"
                :title="`评分策略: ${userAnswerData.scoringStrategy === 0 ? '自定义' : 'AI'}`"
                type="success"
                show-icon
            />            <el-alert v-else title="未设置评分策略" type="warning" show-icon />
          </div>
        </el-card>
      </div>

      <!-- 右侧图片展示 -->
      <div class="image-section" v-if="userAnswerData">
        <el-card class="image-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">结果图片</span>
            </div>
          </template>
          <div class="image-placeholder">
            <!-- 这里放置您的结果图片 -->
            <el-empty description="暂无结果图片" v-if="!userAnswerData.resultPicture" />
            <img v-else :src="userAnswerData.resultPicture" alt="测评结果图片" class="result-image" />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部答题详情卡片（保持不变） -->
    <el-card class="bottom-card">
      <MyUserAnswerPage :appId="appId" @data-loaded="handleDataLoaded" @row-clicked="handleRowClick"/>
    </el-card>
  </div>
</template>

<style scoped>
.result-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.main-content {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.info-section {
  flex: 1;
}

.image-section {
  width: 400px;
}

.info-card, .image-card, .bottom-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.card-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-list {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 改为从左开始对齐 */
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-value {
  font-size: 18px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center; /* 让值靠右对齐 */
  gap: 8px;
  text-align: right; /* 文本右对齐 */
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 18px;
  width: 100px;
  font-weight: 500;
  color: #606266;
}


.description-text {
  color: #606266;
  word-wrap: break-word;  /* 允许长单词或URL换行 */
  white-space: pre-wrap;  /* 保留空白符序列，但正常地进行换行 */
  overflow-wrap: break-word;  /* 在适当的断字点换行 */
  max-width: 100%;  /* 确保不超过容器宽度 */
  display: inline-block;  /* 使max-width生效 */
  text-align: left;
}

.id-code {
  font-family: monospace;
  background-color: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.time-text {
  color: #909399;
}

.user-info {
  align-items: center;
}

.user-name {
  color: #606266;
}

.additional-info {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.image-placeholder {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.result-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.bottom-card {
  margin-top: 20px;
}
</style>